package me.spring.cloud.common.components.oauth2.exception.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import me.spring.cloud.common.components.oauth2.exception.CustomOauthException;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @description: 异常信息序列化
 * @author: luffy
 * @create: 2018-09-17 14:07
 **/
public class CustomOauthExceptionSerializer extends StdSerializer<CustomOauthException> {

  public CustomOauthExceptionSerializer() {
    super(CustomOauthException.class);
  }

  @Override
  public void serialize(CustomOauthException value, JsonGenerator gen, SerializerProvider provider)
      throws IOException {
    HttpServletRequest request = (
        (ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes()).getRequest();

    gen.writeStartObject();
    gen.writeStringField("error", String.valueOf(value.getHttpErrorCode()));
    gen.writeStringField("message", value.getMessage());
    gen.writeStringField("path", request.getServletPath());
    gen.writeStringField("timestamp", String.valueOf(System.currentTimeMillis()));
    if (value.getAdditionalInformation() != null) {
      for (Map.Entry<String, String> entry : value.getAdditionalInformation().entrySet()) {
        String key = entry.getKey();
        String add = entry.getValue();
        gen.writeStringField(key, add);
      }
    }
    gen.writeEndObject();
  }
}
